# -*- coding: utf-8 -*-
"""
Created on Thu Nov  8 20:53:09 2018

@author: 陈忠涛
"""

import tushare as ts
import time
from dateutil.parser import parse
import matplotlib.pyplot as plt

# 数据处理函数
def getData_new(data):
    data.index = range(1,len(data) + 1)
    new_data_reslut = data.drop(['open', 'high', 'low', 'pre_close', 'change', 'pct_change', 'vol', 'amount'], axis = 1)
    new_month = []
    for m in new_data_reslut['trade_date']:
        tra_mon = time.strptime(str(parse(m)),'%Y-%m-%d %H:%M:%S').tm_mon
        new_month.append(tra_mon)
    new_data_reslut['month'] = new_month
    return new_data_reslut


pro = ts.pro_api('825410040c51564426e75325e01bfc180c9fa195f3c1db6312c29283') # 初始化pro接口
# 股票信息列表
d_list = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
print(d_list)
print('==========================================================')

data_pingan = pro.daily(ts_code='000001.SZ', start_date='20180101', end_date='20181231')  # 平安银行
data_guonong = pro.daily(ts_code='000004.SZ', start_date='20180101', end_date='20181231')  # 国农科技

# 平安银行
new_pingan = getData_new(data_pingan)
print(new_pingan)
# 国农科技
new_guonong = getData_new(data_guonong)
print(new_guonong)

# 绘制平安银行和国农科技2018年每个月的股票收盘价的平均值
plt.title('2018:Average stock closing price per month')
plt.xlabel('month')
plt.ylabel('close_mean')
# plt.figure(figsize=(8,6),dpi=80)

p_mean = new_pingan.groupby('month').close.mean() # 平安银行每个月的股票收盘价的平均值
print('平安银行：', p_mean)
# 使用绘画--折线图
p_x = p_mean.index
p_y = p_mean.values
plt.subplot(211) # 多子图
# plt.axes([.1,.1,0.8,0.8]) # 子图
plt.bar(p_x, p_y)
plt.legend(loc='upper left')

g_mean = new_guonong.groupby('month').close.mean() # 国农科技每个月的股票收盘价的平均值
print('国农科技：', g_mean)
# 使用绘画--折线图
g_x = g_mean.index
g_y = g_mean.values
plt.subplot(212)  # 多子图
# plt.axes([.3,.15,0.4,0.3]) # 子图
plt.plot(g_x, g_y, color='green', linestyle='--',linewidth = 2, marker='o',label='Guo Nong')
plt.legend(loc='upper left')